"""Authentication decorators.

These functions are used as Python decorators around views to ensure that the
user is logged in and has the correct permissions to access the view.
"""

from django.conf import settings
from django.http import HttpResponseRedirect
from django.utils.http import urlquote
from hcp.auth.core import REDIRECT_FIELD_NAME
from hcp.jinja import render_to_response

def _redirect_to_login(request):
    return HttpResponseRedirect('%s?%s=%s' % (
        settings.LOGIN_URL,
        REDIRECT_FIELD_NAME,
        urlquote(request.get_full_path())
    ))

def login_required(function):
    def wrapper(request, *args, **kwargs):
        if request.user is None:
            return _redirect_to_login(request)
        else:
            return function(request, *args, **kwargs)

    return wrapper

def permission_required(permission):
    def wrapper(view_func):
        def wrapper2(request, *args, **kwargs):
            if request.user is None:
                return _redirect_to_login(request)
            else:
                if ('superuser' in request.user.hcpPermission or
                    permission in request.user.hcpPermission
                   ):
                    return view_func(request, *args, **kwargs)
                else:
                    return render_to_response('accounts/permission_denied.html',
                                              request=request)
        return wrapper2
    return wrapper
